<?php


namespace api\portal\controller;


use app\admin\model\TombareaRowColModel;
use cmf\controller\RestBaseController;
use think\Db;
use think\Exception;
use tree\Tree;

class CemeteryController extends RestBaseController
{
    // 墓位信息
    public function tombareacol()
    {
        $requst = $this->request;
        $id = $requst->param("id");
        $reacher = $this->getChineseGetValue($_GET['reacher']);
        $userId = $requst->param("userId");
        $token = $requst->param("token");
        $this->LogInOrNot($userId, $token);
        $data = Db::name("tombarea_row")->alias("r")->field("r.rowID,t.align,t.row")
            ->join("dj_tombarea t", "t.id = r.tombarea_id", "left")
            ->where(array('t.id' => $id, 't.status' => 1))->select()->toArray();
        for ($i = 0; $i < count($data); $i++) {
            $col = Db::name("tombarea_row_col")->alias("c")
                ->field("c.colID,c.num,c.reacher,c.col_status,p.selling_price,p.tomb_regulation,p.new_pro,p.tom_img")
                ->join("dj_tombarea_information_product p", "c.colID = p.tomb_id", "left")
                ->where(array('c.rowid' => $data[$i]["rowID"], 'c.status' => ['>', '1,2']))->select();
            $col_data = [];
            foreach ($col as $kc => &$value) {
                $info = Db::name("order")->alias("o")
                    ->field("o.order_id,ad.deceased_name,ci.id customer_id,ci.buyer_name,o.selling_price,o.contract_sn,o.shoppingguide,u.user_nickname")
                    ->join("dj_customer_info ci", "o.customer_id = ci.id", "left")
                    ->join("dj_archives_deceased ad", "o.customer_id = ad.customer_id", "left")
                    ->join("dj_user u","u.id = o.shoppingguide","left")
                    ->where(['o.tomb_id' => $value['colID']])->where("o.status=0 or o.status=1 or o.status=2")
                    ->find();

                $col_info = [
                    'colID' => $value['colID'],
                    'num' => $value['num'],
                    'col_status' => $value['col_status'],
                    'new_pro' => $value['new_pro'],
                    'reacher' => $value['reacher'],
                    'selling_price' => $value['selling_price'],
                    'tomb_regulation' => $value['tomb_regulation'],
                    'shoppingguide' => isset($info['shoppingguide']) ? $info['user_nickname'] : '',
                    'contract_sn' => $info['contract_sn'],
                    'deceased_name' => $info['deceased_name'],
                    'order_id' => $info['order_id'],
                    'customer_id' => $info['customer_id'],
                    'buyer_name' => $info['buyer_name'],
                    'tom_img' => $value['tom_img']
                ];
                if ($reacher == trim($value['reacher'])) {
                    $col_info['flag'] = "1";
                } else {
                    $col_info['flag'] = "0";
                }
                $col_data[] = $col_info;
            }

            $data[$i]['col'] = $col_data;
        }
        $result = array(
            'data' => $data
        );
        $this->success("请求成功！", $result);
    }

    /**
     * 根据id查询墓位信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTombareacolById()
    {
        $requst = $this->request;
        $colID = $requst->param("colID");
        $userId = $requst->param("userId");
        $token = $requst->param("token");
        $this->LogInOrNot($userId, $token);
        $col = Db::name("tombarea_row_col")->alias("c")
            ->field("c.colID,c.num,c.reacher,c.col_status,p.selling_price,p.tomb_regulation,p.new_pro,p.tom_img,p.tomb_region,p.tomb_address,p.layer_num,p.tomb_bit_number")
            ->join("dj_tombarea_information_product p", "c.colID = p.tomb_id", "left")
            ->where('c.colID', 'in', $colID)->select();
        $this->success("请求成功！", $col);
    }


    /**
     * @param $parent_id
     * 获取下级
     * @return array|array[]|\array[][]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getChildren($parent_id, $type = '')
    {
        if ($type == '层') {
            $count = 1;
            $res = Db::name("cemetery")->field("id,type,name label,parent_id")->where(array('is_delete' => 0, 'id' => $parent_id))->select()->toArray();
        } else {
            $res = Db::name("cemetery")->field("id,type,name label,parent_id")->where(array('is_delete' => 0, 'parent_id' => $parent_id))->select()->toArray();
            $count = count($res);
        }
        for ($i = 0; $i < $count; $i++) {
            if ($type != '层') {
                $res[$i]["children"] = $this->getChildren($res[$i]["id"]); // 继续获取下级
            }

            if ($res[$i]['type'] == '园' || $res[$i]['type'] == '层') {// 如果该节点是园或者是层的话赋值children
                $tombarea = Db::name("tombarea")->field("id,name label,cemetery_id")
                    ->where(array('status' => 1, 'cemetery_id' => $res[$i]['id']))
                    ->select()
                    ->toArray();
                if ($res[$i]['type'] == '园') {//如果该节点是园直接把墓区赋值
                    if (!empty($tombarea)) {
//                        $res[$i]["childrenTombarea"] = $tombarea;
                        if (count($res[$i]["children"]) == 0) {
                            $res[$i]["children"] = $tombarea;
                        } else {
                            for ($j = 0; $j < count($tombarea); $j++) {
                                array_push($res[$i]["children"], $tombarea[$j]);
                            }
                        }
//                        $res[$i]["children"] = $tombarea;
                    }
                } else { //如果不是继续赋值children
                    if ($type == '层') {
                        $res = $tombarea;
                    } else {
                        $res[$i]["children"] = $tombarea;
                    }
                }

            }
        }
        return $res;
    }


    /**
     * 获取树
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTree()
    {
        header('Access-Control-Allow-Origin: *');
        $requst = $this->request;
        $name = $this->getChineseGetValue($requst->param("name"));// 接收name

        $userId = $requst->param("userId");
        $token = $requst->param("token");
        $this->LogInOrNot($userId, $token);
        if (!empty($name)) {
            $where = array('c.is_delete' => 0);
        } else {
            $where = array('c.is_delete' => 0, 'c.parent_id' => 0);
        }
//        $res = Db::name("cemetery")->field("id,type,name label")
//            ->where($where)is_delete
////            ->where("name", 'like', '%' . $name . '%')
//            ->select()
//            ->toArray();
        $sql = Db::name("cemetery")->alias("c")
            ->field("c.name label,c.id,c.type")
            ->join("dj_tombarea t", "c.id = t.cemetery_id", "left")
            ->join("dj_tombarea_row r", "t.id = r.tombarea_id", "left")
            ->join("dj_tombarea_row_col rc", "r.rowID = rc.rowid", "left")
            ->join("dj_archives_deceased d", "r.rowID = d.tomb_id", "left")
            ->where($where)
            ->where('c.is_delete', 0);
        if (!empty($name)) {
            $sql = $sql->where('rc.num', $name)->whereOr("d.deceased_name", "like", '%' . $name . '%')->order(array("c.list_order" => "ASC"));
        } else {
            $sql = $sql->order(array("c.list_order" => "ASC"));
        }
        $res = $sql->select()->toArray();

//        $sql = $this->cemetery_model->getLastSql();echo $sql;
//        $sql = Db::name("cemetery")->getLastSql();
//        echo $sql;die;
        if (!empty($name)) {//判断name是否有值如果有值只返回当前节点的所有子节点
            if (!empty($res)) {
                $res[0]['children'] = $this->getChildren($res[0]["id"], $res[0]["type"]);
                $result = $res[0];
            } else {
                $result = null;
            }

        } else {// name没有值正常返回
            for ($i = 0; $i < count($res); $i++) {
                $res[$i]['children'] = $this->getChildren($res[$i]["id"]);
            }
            $result = $res;
        }
        $this->success("请求成功！", $result);
    }

    /**
     * 查看
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function view()
    {
        $requst = $this->request;
        $tomb_id = $requst->param('tomb_id');
        $userId = $requst->param("userId");
        $token = $requst->param("token");
        $this->LogInOrNot($userId, $token);
        $res = Db::name("tombarea_row_col")->alias("c")
            ->field("c.col_status,p.tomb_num,p.footprint,p.tomb_regulation,p.tombstone_w,p.tombstone_h,p.single_cavity_size,
            p.green_belt,p.greenbelt_num,p.specifications,p.warranty,p.maintain,p.selling_price,p.tomb_region,
            p.tomb_address,p.layer_num,p.tomb_bit_number,p.tom_img")
            ->leftJoin("tombarea_information_product p", "c.colID= p.tomb_id")
            ->where("c.colID", $tomb_id)
            ->find();
        $this->success("请求成功！", $res);
    }

    /**
     * 获取抵顶人
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getReacherList()
    {
        $requst = $this->request;
        $userId = $requst->param("userId");
        $token = $requst->param("token");
        $this->LogInOrNot($userId, $token);
        $data = Db::name("tombarea_row_col")->field("reacher")->where("reacher", "<>", "")->distinct(true)->select()->toArray();
        $data[count($data)]['reacher'] = "自营";
        $data = array_reverse($data);
        $this->success("请求成功！", $data);
    }

    //文件上传提交

    public function upload()

    {

        //获取表单上传文件
        $requst = $this->request;
        $userId = $requst->param("userId");
        $token = $requst->param("token");
        $this->LogInOrNot($userId, $token);
        $file = request()->file('file');

        if (empty($file)) {

            $this->error('请选择上传文件');

        }
        //移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move('../public/upload/badlogimage');
        if ($info) {
            $file_name = str_replace("\\", "/", $info->getSaveName());
            $file_path = '/upload/badlogimage/' . $file_name;
            $this->success('文件上传成功', $file_path);
//            echo $info->getFilename();
        } else {
            //上传失败获取错误信息
            $this->error($file->getError());
        }
    }

    /**
     * 不良记录添加
     */
    public function insertBadLog()
    {
        try {
            header('Access-Control-Allow-Origin: *');
            $post = @file_get_contents('php://input');
            $post = json_decode($post, true);
            $userId = $post['verification']['userId'];
            $token = $post['verification']['token'];
            $this->LogInOrNot($userId, $token);
//            $this->success("2",$post['badlog']);die;
            $flag = Db::name("badlog")->insert($post['badlog']);
            if ($flag == 1) {
                $this->success("请求成功！", $flag);
            } else {
                $this->error("请求失败！", $flag);
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }


    }


}